﻿using CDEPMS_API.Utils;
using Newtonsoft.Json.Linq;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Web.UI.WebControls;

using System.Runtime.Caching;
using System.Web.Caching;
using CDEPMS_API.Entities;

namespace CDEPMS_API.Controllers
{
    public class CaptchaController : BaseApiController
    {
        [HttpGet]
        [Obsolete]
        public IHttpActionResult getCaptcha()
        {
            
            //HttpRequestMessage request
          
            //// 获取请求者的IP地址
            //string clientIP = request.Properties.ContainsKey("MS_HttpContext") ?
            //                  ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress :
            //                  request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name) ?
            //                  ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address :
            //                  null;
            //// 保存验证码信息
            //string verifyKey = "captcha_" + clientIP + "_" + random;

            // 使用默认的缓存实例
            var defaultCache = MemoryCache.Default;

            Random randomx = new Random();
            //string verifyKey = "captcha_" + random;

            string capText = CaptchaUtil.CaptchaTextCreator();
            string capStr = capText.Substring(0, capText.LastIndexOf("@")); // 8+1=？
            string code = capText.Substring(capText.LastIndexOf("@") + 1); // 答案=9

            string UUID = Guid.NewGuid().ToString();

            // 添加一个缓存项，设置过期时间为5分钟
            defaultCache.Add(UUID, code, DateTimeOffset.UtcNow.AddMinutes(5));

            string ImageUrl = "";

            var memoryStream = new MemoryStream();

            int width = 120;
            int height = 40;
            int fontSize = 20;

            SKImageInfo imgInfo = new SKImageInfo(width, height);

            using (var surface = SKSurface.Create(imgInfo))
            {
                var canvas = surface.Canvas;
                canvas.Clear(SKColors.White);
                canvas.Translate(width / 2, height / 2);

                for (int i = 0; i < capStr.Length; i++)
                {
                    double px = -capStr.Length / 2.5 * fontSize + fontSize * i;
                    var y = randomx.Next(20) - 20 / 2;
                    var coord = new SKPoint((int)px, 10);
                    var paint = new SKPaint()
                    {
                        Color = new SKColor((byte)randomx.Next(255), (byte)randomx.Next(255), (byte)randomx.Next(255)),
                        IsAntialias = true, // 抗锯齿
                        Style = SKPaintStyle.Fill,
                        TextAlign = SKTextAlign.Center,
                        TextSize = fontSize,
                        TextScaleX = (float)randomx.NextDouble() + 1,
                        Typeface = SKTypeface.FromFamilyName("Microsoft YaHei", SKFontStyle.Normal)
                    };
                    float rr = (float)(randomx.NextDouble() / 2 - 0.25);
                    canvas.RotateRadians(rr);
                    canvas.DrawText(capStr[i].ToString(), coord, paint);
                    canvas.RotateRadians(-rr);
                }

                using (var image = surface.Snapshot())
                {
                    image.Encode(SKEncodedImageFormat.Png, 80).SaveTo(memoryStream);

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    ImageUrl = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());
                }
            }

            return ReturnSuccess(new { UUID, ImageUrl });
        }
    }
}
